package flashSecurityServer.handler;

import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.DefaultWriteRequest;
import org.apache.mina.core.write.WriteRequest;

import flashSecurityServer.log.EbocyLogManager;

public class MessageFilter extends IoFilterAdapter{
	protected static Logger logger = EbocyLogManager.getSystemLogger();
	private static long resceive_num=0;
	private static long send_num=0;
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session,
			Object message) throws Exception {
		resceive_num++;
		IoBuffer buffer=(IoBuffer)message;

		String s=new String(buffer.array(),Charset.forName("utf-8")).trim();
		if(!s.equalsIgnoreCase(PolicyFileLoader.POLICY_FILE_REQUEST_HEADER)){
			super.messageReceived(nextFilter, session,message);
		}else {
			session.write(IoBuffer.wrap(PolicyFileLoader.getPolicyFileContent().getBytes()));
		}
	}
	@Override
	public void filterWrite(NextFilter nextFilter, IoSession session,
			WriteRequest writeRequest) throws Exception {
		if (writeRequest.getMessage() instanceof IoBuffer){
			super.filterWrite(nextFilter, session,writeRequest);
			logger.info(writeRequest.getMessage());
		}else{
			super.filterWrite(nextFilter, session,new DefaultWriteRequest(IoBuffer.wrap(((String)writeRequest.getMessage()).getBytes(Charset.forName("utf-8")))));
			logger.info(writeRequest.getMessage());
		}

	}
}
